var express = require('express');
var router = express.Router();

// 导入db，操作数据库
const { getAll, getById, exec } = require('../db');

/**
 * 获取最新的两个公告和所有公告
 * GET /notice
 */

router.get('/', async (req, res) => {
	let sql = `SELECT * FROM gg_notice ORDER BY notice_time DESC LIMIT 0,2`;
	const data = await getAll(sql);
	/* 获取所有公告按时间降序 */
	let sql2 =
		`SELECT gg_notice.notice_id,gg_notice.notice_content, gg_notice.notice_time, gg_user.user_name FROM ` +
		`gg_notice LEFT JOIN gg_user ON gg_notice.user_id = gg_user.user_id ORDER BY notice_time DESC`;
	const data2 = await getAll(sql2);

	// 编写响应内容
	res.send({
		code: 0,
		message: '获取公告成功',
		result: {
			data: data,
			data2: data2,
		},
	});
});

/**
 * 新增
 * POST /notice
 */

router.post('/', async (req, res) => {
	const { user_id, notice_content, affected_area } = req.body;
	let sql = `insert into gg_notice (user_id,notice_content,affected_area) values (${user_id},'${notice_content}','${affected_area}')`;
	const data = await exec(sql);
	// 编写响应内容
	res.send({
		code: 0,
		message: '获取公告成功',
		result: {
			notice_id: data.insertId,
			user_id,
			notice_content,
			affected_area,
		},
	});
});

/* 根据公告id修改公告 */
router.put('/:id', async (req, res) => {
	const { id } = req.params;
	const { content } = req.body;
	let sql = `update gg_notice set gg_notice.notice_content='${content}' where gg_notice.notice_id=${id}`;
	const data = await exec(sql);
	res.send({
		code: 0,
		message: '修改公告成功',
		result: {
			notice_id: id,
			notice_content: content,
		},
	});
});

/* 根据公告id删除公告 */
router.delete('/:id', async (req, res) => {
	const { id } = req.params;
	let sql = `delete from gg_notice where notice_id=${id}`;
	await exec(sql);
	res.send({
		code: 0,
		message: '删除成功',
		result: '',
	});
});
module.exports = router;
